<template>
  <view class="room-query-container">
    <view class="page-header">
      <text class="page-title">房间列表</text>
      <text class="page-subtitle">赛程: {{ scheduleName }}</text>
    </view>

    <view class="room-list-section">
      <view class="list-header">
        <view class="header-actions">
          <button class="create-btn" @click="goToCreateRoom">创建房间</button>
          <button class="create-by-model-btn" @click="createRoomByModel">按模型创建</button>
          <button class="find-join-btn" @click="findCreateJoinRoom">查找加入房间</button>
          <text class="list-count">共 {{ totalCount }} 个房间</text>
        </view>
      </view>

      <view v-if="loading" class="loading-container">
        <view class="loading-spinner"></view>
        <text>加载中...</text>
      </view>
      
      <view v-else-if="roomList.length === 0" class="empty-state">
        <text>该赛程下暂无房间</text>
      </view>

      <view v-else class="room-list">
        <view 
          class="room-item" 
          v-for="room in roomList" 
          :key="room.id"
          @click="goToRoomSeats(room)"
        >
          <view class="room-header">
            <text class="room-name">{{ room.name }}</text>
            <view class="room-status" :class="getStatusClass(room.status)">
              {{ getStatusText(room.status) }}
            </view>
          </view>
          
          <view class="room-info">
            <view class="info-row">
              <text class="info-label">房间ID:</text>
              <text class="info-value">{{ room.id }}</text>
            </view>
            <view class="info-row">
              <text class="info-label">房主:</text>
              <text class="info-value">{{ room.owner || '未设置' }}</text>
            </view>
            <view class="info-row">
              <text class="info-label">比赛时间:</text>
              <text class="info-value">{{ formatDate(room.matchTime) }}</text>
            </view>
            <view class="info-row">
              <text class="info-label">获胜模式:</text>
              <text class="info-value">{{ getWinModelText(room.winModel) }}</text>
            </view>
            <view class="info-row">
              <text class="info-label">开始类型:</text>
              <text class="info-value">{{ getStartTypeText(room.startType) }}</text>
            </view>
            <view class="info-row">
              <text class="info-label">座位数:</text>
              <text class="info-value">{{ getSeatCount(room.seats) }}</text>
            </view>
            <view class="info-row">
              <text class="info-label">创建时间:</text>
              <text class="info-value">{{ formatDate(room.createTime) }}</text>
            </view>
          </view>
          
          <view class="room-actions">
            <button class="rule-btn" @click.stop="openRuleModal(room)">规则管理</button>
            <button class="group-btn" @click.stop="goToGroupManage(room)">管理分组</button>
            <button class="rule-page-btn" @click.stop="goToRuleManage(room)">规则页面</button>
            <button class="edit-btn" @click.stop="editRoom(room)">编辑</button>
            <button class="delete-btn" @click.stop="deleteRoom(room)">删除</button>
          </view>
          
          <view class="room-hint">
            <text class="hint-text">点击查看房间席位</text>
          </view>
        </view>
        
        <!-- 加载更多提示 -->
        <view v-if="loadingMore" class="loading-more">
          <view class="loading-spinner"></view>
          <text>加载更多...</text>
        </view>
        
        <!-- 没有更多数据提示 -->
        <view v-else-if="!hasMore && roomList.length > 0" class="no-more">
          <text>没有更多数据了</text>
        </view>
      </view>
    </view>
    
    <!-- 房间规则管理模态框 -->
    <view class="modal-overlay" v-if="showRuleModal" @click="closeRuleModal">
      <view class="modal-content" @click.stop>
        <view class="modal-header">
          <text class="modal-title">房间规则管理</text>
          <button class="close-btn" @click="closeRuleModal">×</button>
        </view>
        
        <view class="modal-body">
          <view class="rule-info">
            <text class="rule-label">房间: {{ currentRoom?.name }}</text>
          </view>
          
          <view class="rule-section">
            <view class="section-header">
              <text class="section-title">房间规则列表</text>
              <button class="add-btn" @click="openAddRuleModal">添加规则</button>
            </view>
            
            <view v-if="ruleLoading" class="loading-container">
              <view class="loading-spinner"></view>
              <text>加载中...</text>
            </view>
            
            <view v-else-if="ruleList.length === 0" class="empty-state">
              <text>暂未设置房间规则</text>
            </view>
            
            <view v-else class="rule-list">
              <view 
                class="rule-item" 
                v-for="rule in ruleList" 
                :key="rule.id"
              >
                <view class="rule-content">
                  <view class="rule-header">
                    <text class="rule-id">规则ID: {{ rule.id }}</text>
                    <view class="rule-actions">
                      <button class="edit-rule-btn" @click="editRule(rule)">编辑</button>
                      <button class="delete-rule-btn" @click="deleteRule(rule)">删除</button>
                    </view>
                  </view>
                  <view class="rule-details">
                    <view class="detail-row">
                      <text class="detail-label">起始点:</text>
                      <text class="detail-value">{{ rule.startPoint || '未设置' }}</text>
                    </view>
                    <view class="detail-row">
                      <text class="detail-label">结束点:</text>
                      <text class="detail-value">{{ rule.endPoint || '未设置' }}</text>
                    </view>
                    <view class="detail-row">
                      <text class="detail-label">准备时间:</text>
                      <text class="detail-value">{{ formatTime(rule.prepareTime) }}</text>
                    </view>
                    <view class="detail-row">
                      <text class="detail-label">限制时间:</text>
                      <text class="detail-value">{{ formatTime(rule.limitTime) }}</text>
                    </view>
                    <view class="detail-row">
                      <text class="detail-label">回合数:</text>
                      <text class="detail-value">{{ rule.round || '未设置' }}</text>
                    </view>
                    <view class="detail-row">
                      <text class="detail-label">得分模式:</text>
                      <text class="detail-value">{{ getScoreModelText(rule.scoreModel) }}</text>
                    </view>
                    <view class="detail-row">
                      <text class="detail-label">对战模式:</text>
                      <text class="detail-value">{{ getBattleModelText(rule.battleModel) }}</text>
                    </view>
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 添加/编辑规则模态框 -->
    <view class="modal-overlay" v-if="showRuleFormModal" @click="closeRuleFormModal">
      <view class="modal-content rule-form-modal" @click.stop>
        <view class="modal-header">
          <text class="modal-title">{{ isEditingRule ? '编辑规则' : '添加规则' }}</text>
          <button class="close-btn" @click="closeRuleFormModal">×</button>
        </view>
        
        <view class="modal-body">
          <view class="form-section">
            <view class="form-item">
              <text class="form-label">起始点</text>
              <input 
                class="form-input" 
                v-model="ruleForm.startPoint" 
                placeholder="请输入起始点"
              />
            </view>
            
            <view class="form-item">
              <text class="form-label">结束点</text>
              <input 
                class="form-input" 
                v-model="ruleForm.endPoint" 
                placeholder="请输入结束点"
              />
            </view>
            
            <view class="form-item">
              <text class="form-label">准备时间（秒）</text>
              <input 
                class="form-input" 
                v-model="ruleForm.prepareTimeSeconds" 
                type="number"
                placeholder="请输入准备时间（秒）"
              />
            </view>
            
            <view class="form-item">
              <text class="form-label">限制时间（秒）</text>
              <input 
                class="form-input" 
                v-model="ruleForm.limitTimeSeconds" 
                type="number"
                placeholder="请输入限制时间（秒）"
              />
            </view>
            
            <view class="form-item">
              <text class="form-label">回合数</text>
              <input 
                class="form-input" 
                v-model="ruleForm.round" 
                type="number"
                placeholder="请输入回合数"
              />
            </view>
            
            <view class="form-item">
              <text class="form-label">得分模式</text>
              <view class="form-picker" @click="openScoreModelPicker">
                <view class="picker-text">{{ scoreModelOptions[scoreModelIndex] || '请选择得分模式' }}</view>
                <view class="picker-arrow">▼</view>
              </view>
            </view>
            
            <view class="form-item">
              <text class="form-label">对战模式</text>
              <view class="form-picker" @click="openBattleModelPicker">
                <view class="picker-text">{{ battleModelOptions[battleModelIndex] || '请选择对战模式' }}</view>
                <view class="picker-arrow">▼</view>
              </view>
            </view>
          </view>
        </view>
        
        <view class="modal-footer">
          <button class="cancel-btn" @click="closeRuleFormModal">取消</button>
          <button class="submit-btn" @click="saveRule" :disabled="submitting">
            {{ submitting ? '保存中...' : '保存' }}
          </button>
        </view>
      </view>
    </view>
    
    <!-- 得分模式选择模态框 -->
    <view class="modal-overlay" v-if="showScoreModelPicker" @click="closeScoreModelPicker">
      <view class="picker-modal-content" @click.stop>
        <view class="picker-modal-header">
          <text class="picker-modal-title">选择得分模式</text>
          <button class="close-btn" @click="closeScoreModelPicker">×</button>
        </view>
        <view class="picker-modal-body">
          <view 
            class="picker-option" 
            v-for="(option, index) in scoreModelOptions" 
            :key="index"
            @click="selectScoreModel(index)"
            :class="{ 'selected': scoreModelIndex === index }"
          >
            <text class="option-text">{{ option }}</text>
            <view class="option-check" v-if="scoreModelIndex === index">✓</view>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 对战模式选择模态框 -->
    <view class="modal-overlay" v-if="showBattleModelPicker" @click="closeBattleModelPicker">
      <view class="picker-modal-content" @click.stop>
        <view class="picker-modal-header">
          <text class="picker-modal-title">选择对战模式</text>
          <button class="close-btn" @click="closeBattleModelPicker">×</button>
        </view>
        <view class="picker-modal-body">
          <view 
            class="picker-option" 
            v-for="(option, index) in battleModelOptions" 
            :key="index"
            @click="selectBattleModel(index)"
            :class="{ 'selected': battleModelIndex === index }"
          >
            <text class="option-text">{{ option }}</text>
            <view class="option-check" v-if="battleModelIndex === index">✓</view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref } from 'vue'
import { onLoad, onReachBottom } from '@dcloudio/uni-app'
import { MatchRoomAPI, MatchRoomRuleAPI, BattleAPI, MatchRoomGroupAPI, MatchScheduleAPI } from '@/api/battle.js'

const loading = ref(false)
const roomList = ref([])
const scheduleId = ref('')
const scheduleName = ref('')

// 分页相关数据
const currentPage = ref(0)
const pageSize = ref(20)
const hasMore = ref(true)
const loadingMore = ref(false)
const totalCount = ref(0)

// 规则管理相关数据
const showRuleModal = ref(false)
const showRuleFormModal = ref(false)
const ruleLoading = ref(false)
const submitting = ref(false)
const currentRoom = ref(null)
const ruleList = ref([])
const isEditingRule = ref(false)
const currentRule = ref(null)

// 选择器相关数据
const showScoreModelPicker = ref(false)
const showBattleModelPicker = ref(false)

// 规则表单数据
const ruleForm = ref({
  startPoint: '',
  endPoint: '',
  prepareTimeSeconds: '',
  limitTimeSeconds: '',
  round: '',
  scoreModel: 0,
  battleModel: 0
})

const scoreModelIndex = ref(0)
const battleModelIndex = ref(0)

// 状态映射
const statusMap = {
  1: '等待',
  2: '准备',
  3: '倒计时',
  4: '开始比赛',
  5: '结束比赛',
  6: '暂停',
  7: '取消/终止',
  8: '异常'
}

// 状态样式映射
const statusClassMap = {
  1: 'status-wait',
  2: 'status-prepare',
  3: 'status-countdown',
  4: 'status-start',
  5: 'status-stop',
  6: 'status-pause',
  7: 'status-cancel',
  8: 'status-error'
}

// 获胜模式映射
const winModelMap = {
  1: '一回合 抢1分',
  2: '三回合 抢2分',
  3: '五回合 抢3分',
  4: '高分',
  5: 'BO3',
  6: 'AO5',
  7: 'BAO5',
  8: '时间短',
  9: '步数短',
  10: '距离长',
  11: '五局（抢3） 五回合（抢3）'
}

// 开始类型映射
const startTypeMap = {
  0: '定时开赛',
  1: '手动开赛',
  2: '人满即开'
}

// 得分模式映射
const scoreModelMap = {
  0: '不记分',
  1: '时间短',
  2: '时间长',
  3: '距离短',
  4: '距离长',
  5: '得分少',
  6: '得分多',
  7: '步数短',
  8: '步数长'
}

// 对战模式映射
const battleModelMap = {
  0: '接力',
  1: '单回合',
  2: '多回合'
}

const scoreModelOptions = [
  '不记分',
  '时间短',
  '时间长',
  '距离短',
  '距离长',
  '得分少',
  '得分多',
  '步数短',
  '步数长'
]

const battleModelOptions = [
  '接力',
  '单回合',
  '多回合'
]

const getStatusText = (status) => statusMap[status] || '未知'
const getStatusClass = (status) => statusClassMap[status] || 'status-unknown'
const getWinModelText = (winModel) => winModelMap[winModel] || '未知'
const getStartTypeText = (startType) => startTypeMap[startType] || '未知'
const getScoreModelText = (scoreModel) => scoreModelMap[scoreModel] || '未知'
const getBattleModelText = (battleModel) => battleModelMap[battleModel] || '未知'

const formatDate = (timestamp) => {
  if (!timestamp) return '未设置'
  const date = new Date(timestamp)
  return date.toLocaleString('zh-CN')
}

const formatTime = (milliseconds) => {
  if (!milliseconds) return '未设置'
  const seconds = Math.floor(milliseconds / 1000)
  return `${seconds}秒`
}

const getSeatCount = (seats) => {
  if (!seats) return 0
  return Array.isArray(seats) ? seats.length : 0
}

const fetchRooms = async (isLoadMore = false) => {
  if (!scheduleId.value) return;
  
  console.log('fetchRooms被调用', {
    isLoadMore,
    scheduleId: scheduleId.value,
    currentPage: currentPage.value,
    pageSize: pageSize.value
  })
  
  if (isLoadMore) {
    if (!hasMore.value || loadingMore.value) {
      console.log('跳过加载更多：hasMore或loadingMore为false')
      return;
    }
    loadingMore.value = true
  } else {
    loading.value = true
    // 重置分页状态
    currentPage.value = 0
    hasMore.value = true
    roomList.value = []
  }
  
  try {
    const result = await MatchRoomAPI.page({ 
      matchScheduleId: scheduleId.value,
      pageNum: currentPage.value,
      pageSize: pageSize.value
    })
    console.log('房间查询API返回结果:', result)
    if (result.code === 0) {
      const newRooms = result.data?.list || result.data || []
      totalCount.value = result.data?.totalCount || 0
      
      console.log('API返回数据', {
        newRoomsLength: newRooms.length,
        totalCount: totalCount.value,
        isLoadMore
      })
      
      if (isLoadMore) {
        // 加载更多时，追加数据
        roomList.value = [...roomList.value, ...newRooms]
      } else {
        // 首次加载时，替换数据
        roomList.value = newRooms
      }
      
      // 判断是否还有更多数据
      hasMore.value = newRooms.length === pageSize.value
      if (hasMore.value) {
        currentPage.value++
      }
      
      console.log('数据加载完成', {
        hasMore: hasMore.value,
        currentPage: currentPage.value,
        totalRooms: roomList.value.length
      })
    } else {
      if (!isLoadMore) {
        roomList.value = []
      }
      throw new Error(result.msg || '获取房间失败')
    }
  } catch (error) {
    console.error('获取房间失败:', error)
    if (!isLoadMore) {
      roomList.value = []
    }
    uni.showToast({
      title: error.message || '获取房间失败',
      icon: 'none'
    })
  } finally {
    if (isLoadMore) {
      loadingMore.value = false
    } else {
      loading.value = false
    }
  }
}

// 加载更多房间
const loadMoreRooms = () => {
  console.log('loadMoreRooms被调用', {
    hasMore: hasMore.value,
    loadingMore: loadingMore.value,
    currentPage: currentPage.value,
    roomListLength: roomList.value.length
  })
  
  // 防止重复加载
  if (!hasMore.value || loadingMore.value) {
    console.log('跳过加载更多：', {
      hasMore: hasMore.value,
      loadingMore: loadingMore.value
    })
    return
  }
  
  console.log('开始加载更多数据，当前页码：', currentPage.value)
  fetchRooms(true)
}

// 重置并重新加载
const refreshRooms = () => {
  fetchRooms(false)
}

onLoad((options) => {
  if (options.scheduleId) {
    scheduleId.value = options.scheduleId
    scheduleName.value = decodeURIComponent(options.scheduleName || '')
    fetchRooms()
  }
})

// 页面滚动到底部时触发
onReachBottom(() => {
  console.log('页面滚动到底部，开始加载更多数据')
  loadMoreRooms()
})

// 跳转到创建房间页面
const goToCreateRoom = () => {
  uni.navigateTo({
    url: `/views/room-create?scheduleId=${scheduleId.value}&scheduleName=${encodeURIComponent(scheduleName.value)}`
  })
}

// 查找创建加入房间
const findCreateJoinRoom = async () => {
  try {
    // 显示加载提示
    uni.showLoading({
      title: '查找房间中...'
    })
    
    // 调用findCreateJoinRoom API
    const result = await BattleAPI.findCreateJoinRoom({
      matchScheduleId: scheduleId.value
    })
    
    console.log('findCreateJoinRoom API返回结果:', result)
    
    if (result.code === 0) {
      // 处理成功结果
      if (result.data) {
        // 如果找到了可加入的房间，显示结果
        uni.showModal({
          title: '查找结果',
          content: `找到可加入的房间: ${result.data.roomName || '未知房间'}`,
          showCancel: false,
          success: () => {
            // 可以在这里添加跳转到房间的逻辑
            console.log('找到的房间信息:', result.data)
          }
        })
      } else {
        // 没有找到可加入的房间
        uni.showModal({
          title: '查找结果',
          content: '当前没有可加入的房间，是否创建新房间？',
          success: (res) => {
            if (res.confirm) {
              goToCreateRoom()
            }
          }
        })
      }
    } else {
      throw new Error(result.msg || '查找房间失败')
    }
  } catch (error) {
    console.error('findCreateJoinRoom失败:', error)
    uni.showToast({
      title: error.message || '查找房间失败',
      icon: 'none'
    })
  } finally {
    uni.hideLoading()
  }
}

// 按模型创建房间
const createRoomByModel = async () => {
  try {
    // 显示加载提示
    uni.showLoading({
      title: '按模型创建房间中...'
    })
    
    // 使用 MatchScheduleAPI.page 查询赛程详情
    const scheduleResult = await MatchScheduleAPI.page({
      matchScheduleId: scheduleId.value,
      pageNum: 0,
      pageSize: 1
    })
    
    if (scheduleResult.code !== 0) {
      throw new Error('获取赛程详情失败')
    }
    
    // 从赛程详情中获取赛程模型ID
    const scheduleInfo = scheduleResult.data?.list?.[0] || scheduleResult.data?.[0]
    const matchScheduleModelId = scheduleInfo?.matchScheduleModelId
    
    if (!matchScheduleModelId) {
      throw new Error('当前赛程未配置赛程模型，无法按模型创建房间')
    }
    
    // 调用createRoomByModel API
    const result = await BattleAPI.createRoomByModel({
      matchScheduleModelId: matchScheduleModelId,  // 使用赛程模型ID
      matchScheduleId: scheduleId.value,           // 赛程ID
      matchRoomId: `room_${Date.now()}`            // 生成唯一的房间ID
    })
    
    console.log('createRoomByModel API返回结果:', result)
    
    if (result.code === 0) {
      uni.showToast({
        title: '按模型创建房间成功',
        icon: 'success'
      })
      
      // 刷新房间列表
      refreshRooms()
    } else {
      throw new Error(result.msg || '按模型创建房间失败')
    }
  } catch (error) {
    console.error('createRoomByModel失败:', error)
    uni.showToast({
      title: error.message || '按模型创建房间失败',
      icon: 'none'
    })
  } finally {
    uni.hideLoading()
  }
}

// 编辑房间
const editRoom = (room) => {
  uni.navigateTo({
    url: `/views/room-edit?roomId=${room.id}&scheduleId=${scheduleId.value}&scheduleName=${encodeURIComponent(scheduleName.value)}`
  })
}

// 删除房间
const deleteRoom = (room) => {
  uni.showModal({
    title: '确认删除',
    content: `确定要删除房间 "${room.name}" 吗？`,
    success: async (res) => {
      if (res.confirm) {
        try {
          const result = await MatchRoomAPI.remove({
            matchRoomId: room.id
          })
          
          if (result.code === 0) {
            uni.showToast({
              title: '删除成功',
              icon: 'success'
            })
            refreshRooms()
          } else {
            throw new Error(result.msg || '删除失败')
          }
        } catch (error) {
          console.error('删除房间失败:', error)
          uni.showToast({
            title: error.message || '删除失败',
            icon: 'none'
          })
        }
      }
    }
  })
}

// 打开规则管理模态框
const openRuleModal = (room) => {
  currentRoom.value = room
  showRuleModal.value = true
  loadRuleList()
}

// 关闭规则管理模态框
const closeRuleModal = () => {
  showRuleModal.value = false
  currentRoom.value = null
  ruleList.value = []
}

// 加载规则列表
const loadRuleList = async () => {
  if (!currentRoom.value) return
  
  ruleLoading.value = true
  try {
    const result = await MatchRoomRuleAPI.page({
      matchRoomId: currentRoom.value.id,
      pageNum: 0,
      pageSize: 100
    })
    
    if (result.code === 0 && result.data) {
      ruleList.value = result.data.list || result.data || []
    } else {
      ruleList.value = []
      throw new Error(result.msg || '获取规则列表失败')
    }
  } catch (error) {
    console.error('获取规则列表失败:', error)
    uni.showToast({
      title: error.message || '获取规则列表失败',
      icon: 'none'
    })
  } finally {
    ruleLoading.value = false
  }
}

// 打开添加规则模态框
const openAddRuleModal = () => {
  isEditingRule.value = false
  currentRule.value = null
  resetRuleForm()
  showRuleFormModal.value = true
}

// 打开编辑规则模态框
const editRule = (rule) => {
  isEditingRule.value = true
  currentRule.value = rule
  fillRuleForm(rule)
  showRuleFormModal.value = true
}

// 关闭规则表单模态框
const closeRuleFormModal = () => {
  showRuleFormModal.value = false
  isEditingRule.value = false
  currentRule.value = null
  resetRuleForm()
}

// 重置规则表单
const resetRuleForm = () => {
  ruleForm.value = {
    startPoint: '',
    endPoint: '',
    prepareTimeSeconds: '',
    limitTimeSeconds: '',
    round: '',
    scoreModel: 0,
    battleModel: 0
  }
  scoreModelIndex.value = 0
  battleModelIndex.value = 0
}

// 填充规则表单
const fillRuleForm = (rule) => {
  ruleForm.value = {
    startPoint: rule.startPoint || '',
    endPoint: rule.endPoint || '',
    prepareTimeSeconds: rule.prepareTime ? Math.floor(rule.prepareTime / 1000) : '',
    limitTimeSeconds: rule.limitTime ? Math.floor(rule.limitTime / 1000) : '',
    round: rule.round || '',
    scoreModel: rule.scoreModel || 0,
    battleModel: rule.battleModel || 0
  }
  scoreModelIndex.value = rule.scoreModel || 0
  battleModelIndex.value = rule.battleModel || 0
}

// 打开得分模式选择器
const openScoreModelPicker = () => {
  showScoreModelPicker.value = true
}

// 打开对战模式选择器
const openBattleModelPicker = () => {
  showBattleModelPicker.value = true
}

// 保存规则
const saveRule = async () => {
  if (!ruleForm.value.startPoint.trim()) {
    uni.showToast({
      title: '请输入起始点',
      icon: 'none'
    })
    return
  }
  
  if (!ruleForm.value.endPoint.trim()) {
    uni.showToast({
      title: '请输入结束点',
      icon: 'none'
    })
    return
  }
  
  submitting.value = true
  try {
    const data = {
      matchRoomId: currentRoom.value.id,
      startPoint: ruleForm.value.startPoint,
      endPoint: ruleForm.value.endPoint,
      prepareTime: ruleForm.value.prepareTimeSeconds ? parseInt(ruleForm.value.prepareTimeSeconds) * 1000 : 0,
      limitTime: ruleForm.value.limitTimeSeconds ? parseInt(ruleForm.value.limitTimeSeconds) * 1000 : 0,
      round: ruleForm.value.round ? parseInt(ruleForm.value.round) : 1,
      scoreModel: ruleForm.value.scoreModel,
      battleModel: ruleForm.value.battleModel
    }
    
    let result
    if (isEditingRule.value) {
      result = await MatchRoomRuleAPI.edit({
        ...data,
        matchRoomRuleId: currentRule.value.id
      })
    } else {
      result = await MatchRoomRuleAPI.create(data)
    }
    
    if (result.code === 0) {
      uni.showToast({
        title: isEditingRule.value ? '更新成功' : '创建成功',
        icon: 'success'
      })
      closeRuleFormModal()
      loadRuleList()
    } else {
      throw new Error(result.msg || (isEditingRule.value ? '更新失败' : '创建失败'))
    }
  } catch (error) {
    console.error('保存规则失败:', error)
    uni.showToast({
      title: error.message || '保存失败',
      icon: 'none'
    })
  } finally {
    submitting.value = false
  }
}

// 删除规则
const deleteRule = (rule) => {
  uni.showModal({
    title: '确认删除',
    content: `确定要删除规则 "${rule.startPoint} -> ${rule.endPoint}" 吗？`,
    success: async (res) => {
      if (res.confirm) {
        try {
          const result = await MatchRoomRuleAPI.remove({
            matchRoomRuleId: rule.id
          })
          
          if (result.code === 0) {
            uni.showToast({
              title: '删除成功',
              icon: 'success'
            })
            loadRuleList()
          } else {
            throw new Error(result.msg || '删除失败')
          }
        } catch (error) {
          console.error('删除规则失败:', error)
          uni.showToast({
            title: error.message || '删除失败',
            icon: 'none'
          })
        }
      }
    }
  })
}

// 跳转到规则管理页面
const goToRuleManage = (room) => {
  uni.navigateTo({
    url: `/views/room-rule-manage?roomId=${room.id}&roomName=${encodeURIComponent(room.name)}`
  })
}

// 关闭得分模式选择模态框
const closeScoreModelPicker = () => {
  showScoreModelPicker.value = false
}

// 关闭对战模式选择模态框
const closeBattleModelPicker = () => {
  showBattleModelPicker.value = false
}

// 选择得分模式
const selectScoreModel = (index) => {
  scoreModelIndex.value = index
  ruleForm.value.scoreModel = index
  closeScoreModelPicker()
}

// 选择对战模式
const selectBattleModel = (index) => {
  battleModelIndex.value = index
  ruleForm.value.battleModel = index
  closeBattleModelPicker()
}

// 跳转到房间席位页面
const goToRoomSeats = (room) => {
  uni.navigateTo({
    url: `/views/cube-battle-room?roomId=${room.id}&roomName=${encodeURIComponent(room.name)}`
  })
}

// 跳转到分组管理页面
const goToGroupManage = (room) => {
  uni.navigateTo({
    url: `/views/group-manage?roomId=${room.id}&roomName=${encodeURIComponent(room.name)}`
  })
}
</script>

<style lang="scss" scoped>
.room-query-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 40rpx;
}

.page-header {
  text-align: center;
  margin-bottom: 60rpx;
  
  .page-title {
    display: block;
    font-size: 48rpx;
    font-weight: bold;
    color: #fff;
    margin-bottom: 20rpx;
    text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.3);
  }
  
  .page-subtitle {
    font-size: 28rpx;
    color: rgba(255, 255, 255, 0.8);
  }
}

.room-list-section {
  .list-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30rpx;
    
    .section-title {
      color: #fff;
      font-size: 32rpx;
      font-weight: bold;
    }
    
    .header-actions {
      display: flex;
      align-items: center;
      gap: 12rpx;
      flex-wrap: wrap;
      
      .create-btn {
        height: 60rpx;
        padding: 0 20rpx;
        border: none;
        border-radius: 12rpx;
        color: #fff;
        font-size: 24rpx;
        font-weight: bold;
        background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
        white-space: nowrap;
      }
      
      .create-by-model-btn {
        height: 60rpx;
        padding: 0 20rpx;
        border: none;
        border-radius: 12rpx;
        color: #fff;
        font-size: 24rpx;
        font-weight: bold;
        background: linear-gradient(135deg, #fd7e14 0%, #ff8c00 100%);
        white-space: nowrap;
      }
      
      .find-join-btn {
        height: 60rpx;
        padding: 0 20rpx;
        border: none;
        border-radius: 12rpx;
        color: #fff;
        font-size: 24rpx;
        font-weight: bold;
        background: linear-gradient(135deg, #007bff 0%, #0056b3 100%);
        white-space: nowrap;
      }
      
      .list-count {
        color: rgba(255, 255, 255, 0.8);
        font-size: 24rpx;
        margin-left: 10rpx;
      }
    }
  }

  .loading-container, .empty-state {
    text-align: center;
    color: #fff;
    padding: 50rpx;
  }
  
  .room-list {
    .room-item {
      background: rgba(255, 255, 255, 0.95);
      border-radius: 20rpx;
      padding: 40rpx;
      margin-bottom: 30rpx;
      box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.2);
      cursor: pointer;
      transition: all 0.3s ease;
      
      &:hover {
        transform: translateY(-5rpx);
        box-shadow: 0 15rpx 40rpx rgba(0, 0, 0, 0.3);
      }
      
      &:active {
        transform: translateY(-2rpx);
      }
      
      .room-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 30rpx;
        
        .room-name {
          font-size: 32rpx;
          font-weight: bold;
          color: #333;
        }
        
        .room-status {
          padding: 8rpx 20rpx;
          border-radius: 20rpx;
          font-size: 24rpx;
          font-weight: bold;
          
          &.status-wait { background: #fff3cd; color: #856404; }
          &.status-prepare { background: #d1ecf1; color: #0c5460; }
          &.status-countdown { background: #d4edda; color: #155724; }
          &.status-start { background: #cce5ff; color: #004085; }
          &.status-stop { background: #f8d7da; color: #721c24; }
          &.status-pause { background: #fff3cd; color: #856404; }
          &.status-cancel { background: #f8d7da; color: #721c24; }
          &.status-error { background: #f8d7da; color: #721c24; }
        }
      }
      
      .room-info {
        .info-row {
          display: flex;
          margin-bottom: 15rpx;
          font-size: 26rpx;
          
          .info-label { width: 160rpx; color: #666; }
          .info-value { flex: 1; color: #333; }
        }
      }
      
      .room-actions {
        display: flex;
        gap: 15rpx;
        margin-top: 20rpx;
        flex-wrap: wrap;
        
        .rule-btn, .group-btn, .rule-page-btn, .edit-btn, .delete-btn {
          padding: 8rpx 20rpx;
          border: none;
          border-radius: 12rpx;
          color: #fff;
          font-size: 24rpx;
          font-weight: bold;
        }
        
        .rule-btn {
          background: linear-gradient(135deg, #007bff 0%, #0056b3 100%);
        }
        
        .group-btn {
          background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
        }
        
        .rule-page-btn {
          background: linear-gradient(135deg, #6c757d 0%, #3a3f44 100%);
        }
        
        .edit-btn {
          background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
        }
        
        .delete-btn {
          background: linear-gradient(135deg, #dc3545 0%, #c82333 100%);
        }
      }
      
      .room-hint {
        margin-top: 15rpx;
        text-align: center;
        
        .hint-text {
          font-size: 24rpx;
          color: #999;
          font-style: italic;
        }
      }
    }
    
    // 加载更多样式
    .loading-more {
      text-align: center;
      padding: 40rpx;
      color: #666;
      
      .loading-spinner {
        width: 40rpx;
        height: 40rpx;
        border: 3rpx solid #f3f3f3;
        border-top: 3rpx solid #667eea;
        border-radius: 50%;
        animation: spin 1s linear infinite;
        margin: 0 auto 15rpx;
      }
      
      text {
        font-size: 26rpx;
      }
    }
    
    // 没有更多数据样式
    .no-more {
      text-align: center;
      padding: 30rpx;
      color: #999;
      
      text {
        font-size: 26rpx;
      }
    }
  }
}

// 规则管理模态框样式
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;
  
  .modal-content {
    width: 90%;
    max-height: 80%;
    background: #fff;
    border-radius: 20rpx;
    overflow: hidden;
    position: relative;
    z-index: 10000;
    
    &.rule-form-modal {
      max-height: 90%;
    }
    
    .modal-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 30rpx;
      border-bottom: 2rpx solid #eee;
      
      .modal-title {
        font-size: 32rpx;
        font-weight: bold;
        color: #333;
      }
      
      .close-btn {
        width: 60rpx;
        height: 60rpx;
        border: none;
        background: none;
        font-size: 40rpx;
        color: #999;
      }
    }
    
    .modal-body {
      padding: 30rpx;
      max-height: 60vh;
      overflow-y: auto;
      
      .rule-info {
        margin-bottom: 30rpx;
        padding: 20rpx;
        background: #f8f9fa;
        border-radius: 12rpx;
        
        .rule-label {
          font-size: 28rpx;
          color: #333;
          font-weight: bold;
        }
      }
      
      .rule-section {
        .section-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 20rpx;
          
          .section-title {
            font-size: 28rpx;
            color: #333;
            font-weight: bold;
          }
          
          .add-btn {
            height: 50rpx;
            padding: 0 20rpx;
            background: #28a745;
            border: none;
            border-radius: 8rpx;
            color: #fff;
            font-size: 24rpx;
          }
        }
        
        .rule-list {
          .rule-item {
            background: #f8f9fa;
            border-radius: 12rpx;
            margin-bottom: 15rpx;
            overflow: hidden;
            
            .rule-content {
              .rule-header {
                display: flex;
                justify-content: space-between;
                align-items: center;
                padding: 20rpx;
                background: #e9ecef;
                
                .rule-id {
                  font-size: 26rpx;
                  color: #333;
                  font-weight: bold;
                }
                
                .rule-actions {
                  display: flex;
                  gap: 10rpx;
                  
                  .edit-rule-btn, .delete-rule-btn {
                    height: 40rpx;
                    padding: 0 15rpx;
                    border: none;
                    border-radius: 6rpx;
                    color: #fff;
                    font-size: 22rpx;
                  }
                  
                  .edit-rule-btn {
                    background: #007bff;
                  }
                  
                  .delete-rule-btn {
                    background: #dc3545;
                  }
                }
              }
              
              .rule-details {
                padding: 20rpx;
                
                .detail-row {
                  display: flex;
                  margin-bottom: 10rpx;
                  font-size: 24rpx;
                  
                  .detail-label {
                    width: 120rpx;
                    color: #666;
                  }
                  
                  .detail-value {
                    flex: 1;
                    color: #333;
                  }
                }
              }
            }
          }
        }
      }
      
      .form-section {
        .form-item {
          margin-bottom: 25rpx;
          position: relative;
          z-index: 1;
          
          .form-label {
            display: block;
            font-size: 26rpx;
            color: #333;
            font-weight: bold;
            margin-bottom: 10rpx;
          }
          
          .form-input {
            width: 100%;
            height: 70rpx;
            padding: 0 15rpx;
            border: 2rpx solid #ddd;
            border-radius: 8rpx;
            font-size: 26rpx;
            background: #fff;
            box-sizing: border-box;
            
            &:focus {
              border-color: #667eea;
            }
          }
          
          .form-picker {
            width: 100%;
            height: 70rpx;
            border: 2rpx solid #ddd;
            border-radius: 8rpx;
            background: #fff;
            position: relative;
            z-index: 2;
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 0 15rpx;
            cursor: pointer;
            box-sizing: border-box;
            
            .picker-text {
              font-size: 26rpx;
              color: #333;
            }
            
            .picker-arrow {
              font-size: 24rpx;
              color: #999;
            }
          }
        }
      }
    }
    
    .modal-footer {
      display: flex;
      gap: 20rpx;
      padding: 30rpx;
      border-top: 2rpx solid #eee;
      
      .cancel-btn, .submit-btn {
        flex: 1;
        height: 80rpx;
        border: none;
        border-radius: 12rpx;
        font-size: 28rpx;
        font-weight: bold;
        
        &.cancel-btn {
          background: #f8f9fa;
          color: #666;
          border: 2rpx solid #eee;
        }
        
        &.submit-btn {
          background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
          color: #fff;
          
          &:disabled {
            opacity: 0.6;
          }
        }
      }
    }
  }
}

.loading-spinner {
  width: 60rpx;
  height: 60rpx;
  border: 4rpx solid #f3f3f3;
  border-top: 4rpx solid #667eea;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin: 0 auto 20rpx;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

// 全局样式，确保picker弹出框在最顶层
:deep(.uni-picker-container) {
  z-index: 99999 !important;
}

:deep(.uni-picker-view) {
  z-index: 99999 !important;
}

:deep(.uni-picker-mask) {
  z-index: 99998 !important;
}

// 选择器模态框样式
.picker-modal-content {
  width: 80%;
  max-height: 70%;
  background: #fff;
  border-radius: 20rpx;
  overflow: hidden;
  position: relative;
  z-index: 10001;
  
  .picker-modal-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 30rpx;
    border-bottom: 2rpx solid #eee;
    background: #f8f9fa;
    
    .picker-modal-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }
    
    .close-btn {
      width: 60rpx;
      height: 60rpx;
      border: none;
      background: none;
      font-size: 40rpx;
      color: #999;
    }
  }
  
  .picker-modal-body {
    max-height: 50vh;
    overflow-y: auto;
    
    .picker-option {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 30rpx;
      border-bottom: 1rpx solid #eee;
      transition: background-color 0.3s ease;
      
      &:hover {
        background: #f8f9fa;
      }
      
      &.selected {
        background: #e3f2fd;
        border-left: 4rpx solid #007bff;
      }
      
      .option-text {
        font-size: 28rpx;
        color: #333;
      }
      
      .option-check {
        font-size: 32rpx;
        color: #007bff;
        font-weight: bold;
      }
    }
  }
}
</style> 